import 'package:flutter/material.dart';
import 'package:x3_base_package/x3_base_package.dart';
import 'package:x3_business_core/business_customer/page/business_customer_details_address_edit.dart';

class BusinessCustomerDetailsEditAddressTab extends StatefulWidget {
  BusinessCustomerDetailsEditAddressTab({Key key, @required this.response, @required this.vipId, this.isChoosePage = false}) : super(key: key);

  final BaseHttpResponseModel response;

  final String vipId;

  final bool isChoosePage;

  @override
  _BusinessCustomerDetailsEditAddressTabState createState() => _BusinessCustomerDetailsEditAddressTabState();
}

class _BusinessCustomerDetailsEditAddressTabState extends State<BusinessCustomerDetailsEditAddressTab> {
  final BaseFutureController _controller = BaseFutureController();

  OperableController _operableController = OperableController();


  @override
  void dispose() {
    _operableController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(child: _buildAddressListViewWidget()),
        _buildFooterWidget(),
      ],
    );
  }

  Widget _buildAddressListViewWidget() {
    return BaseScreenRefreshComponent(
      controller: _controller,
      request: BaseScreenRequestModel('/vipbills/vipuserbills/vipclerk/get/address/{vipid}', params: {'vipid': widget.vipId}, method: BaseHttpMethodEnum.GET),
      needRefreshIndicator: false,
      builder: (BaseHttpResultModel result) {
        _operableController.dataSource = result.data;
        return _buildScaffoldWidget();
      },
    );
  }

  Widget _buildScaffoldWidget() {
    return SingleChildScrollView(
      padding: EdgeInsets.only(bottom: 12),
      child: BaseOperableList(operableController: _operableController, buildItem: _buildListItem),
    );
  }

  Widget _buildListItem(dynamic item, int index) {
    String receiverName = item['receiverName'] ?? '';
    String phoneNum = item['phoneNum'] ?? '';
    String address = (item['province'] ?? '') + (item['city'] ?? '') + (item['area'] ?? '') + (item['detailAddress'] ?? '');
    return BaseCardComponent(
      onTap: widget.isChoosePage == true ? () => _onChooseAddress(item) : null,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          BaseComponentUtils.buildTextSpanWidget([receiverName, phoneNum]),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 16.0),
            child: Row(
              children: [
                _buildListItemLabel(item, index),
                Expanded(child: Text(address, style: Theme.of(context).textTheme.subtitle2)),
              ],
            ),
          ),
          BaseComponentUtils.buildHorizontalDivider(),
          SizedBox(height: 12),
          _buildListViewFooter(item, index),
        ],
      ),
    );
  }

  Widget _buildListItemLabel(Map<String, dynamic> item, int index) {
    String labelName = item['labelName'] ?? '';
    bool isDefault = item['setDefault'] ?? false;
    return Row(
      children: [
        isDefault ? Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(color: Color(0xFFFF004F), borderRadius: BorderRadius.circular(2)),
          padding: EdgeInsets.symmetric(horizontal: 4.0),
          margin: EdgeInsets.only(right: 8.0),
          child: Text('默认', style: Theme.of(context).textTheme.bodyText2.copyWith(color: Colors.white)),
        ) : SizedBox(),
        Container(
          alignment: Alignment.center,
          constraints: BoxConstraints( minWidth: 30.0 ),
          decoration: BoxDecoration(color: Color(0xFF5E96F4), borderRadius: BorderRadius.circular(2)),
          padding: EdgeInsets.symmetric(horizontal: 4.0),
          margin: EdgeInsets.only(right: 8.0),
          child: Text(labelName, style: Theme.of(context).textTheme.bodyText2.copyWith(color: Colors.white)),
        ),
      ],
    );
  }

  Widget _buildListViewFooter(Map<String, dynamic> item, int index) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        BaseButton.two(text: '编辑', fill: false, onPress: () => _onEditAddress(item)),
        SizedBox(width: 12.0),
        BaseButton.two(text: '删除', fill: false, onPress: () => _onDeleteAddress(item['addressId'], index)),
        _buildListViewChooseButton(item, index),
      ],
    );
  }

  Widget _buildListViewChooseButton(Map<String, dynamic> item, int index) {
    return widget.isChoosePage == true ? Container(margin: const EdgeInsets.only(left: 12.0), child: BaseButton.two(text: '选择', fill: false, onPress: () => _onChooseAddress(item))) : Container();
  }

  Widget _buildFooterWidget() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.symmetric( horizontal: 16.0, vertical: 12.0 ),
      child: BaseButton(
        text: '新建收货地址',
        fill: true,
        onPress: () {
          BaseRouterUtil().pushNamed(BusinessCustomerDetailsAddressEdit.sName, arguments: {'vipId': widget.vipId}).then((value) {
            _controller.refresh();
          });
        },
      ),
    );
  }


  void _onEditAddress(Map<String, dynamic> item) {
    BaseRouterUtil().pushNamed(BusinessCustomerDetailsAddressEdit.sName, arguments: {'vipId': widget.vipId, 'dataSource': item}).then((value) {
      _controller.refresh();
    });
  }

  void _onDeleteAddress(String addressId, int index) {
    BaseComponentUtils.showMessageDialog(context, content: '您确定要删除吗？', onOKPress: () {
      Navigator.pop(context);
      BaseComponentUtils.showLoadingDialog(context, hint: '正在删除中');
      dioUtil.fetch('/vip/addressmanage/del/$addressId', method: BaseHttpMethodEnum.DELETE).then((BaseHttpResultModel result) {
        BaseComponentUtils.hideLoadingDialog(context);
        if (result.success == true) {
          if (_operableController.dataSource[index]['setDefault'] == true) {
            _resetSetDefault();
          }
          this._operableController.remove(index: index);
        }
      });
    });
  }

  void _resetSetDefault() {
    _operableController.dataSource.forEach((element) {
      element['setDefault'] = false;
    });
  }

  void _onChooseAddress(Map<String, dynamic> item) {
    BaseRouterUtil.getInstance().pop(item);
  }

}
